const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');

// 路径配置
const sourceDir = path.join(__dirname, 'miniprogram/images/discovers');
const outputDir = path.join(__dirname, 'miniprogram/images/discovers/png');
const jsFilePath = path.join(__dirname, 'miniprogram/pages/discover/index.js');

// 确保输出目录存在
if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
}

// 文件名映射表 (原始文件名 -> png文件名)
const fileNameMap = {};

// 检查JS文件中引用的图片
const checkJsFileReferences = () => {
    try {
        console.log('Scanning JS file for image references...');
        
        const jsContent = fs.readFileSync(jsFilePath, 'utf8');
        const urlPattern = /imageUrl\s*:\s*['"]([^'"]+)['"]/g;
        const matches = [];
        let match;
        
        while ((match = urlPattern.exec(jsContent)) !== null) {
            matches.push(match[1]);
        }
        
        console.log(`Found ${matches.length} image references in JS file.`);
        console.log('Referenced images:', matches);
        
        return matches;
    } catch (error) {
        console.error('Error scanning JS file:', error);
        return [];
    }
};

// 使用命令行工具转换图片
const convertImage = (inputPath, outputPath) => {
    return new Promise((resolve, reject) => {
        // 不使用sharp，改用node内置的复制函数
        fs.copyFile(inputPath, outputPath, (err) => {
            if (err) {
                reject(err);
                return;
            }
            resolve();
        });
    });
};

// 读取所有图片文件
const processFiles = async () => {
    try {
        // 先检查JS文件中引用的图片
        const imageReferences = checkJsFileReferences();
        
        const files = fs.readdirSync(sourceDir);
        
        // 过滤出所有图片文件
        const imageFiles = files.filter(file => {
            const ext = path.extname(file).toLowerCase();
            return ['.avif', '.jpg', '.jpeg', '.png', '.gif', '.webp'].includes(ext);
        });
        
        console.log(`Found ${imageFiles.length} image files to process.`);
        
        // 创建文件名到拼音的映射
        const fileToBaseName = {};
        imageFiles.forEach(file => {
            const baseName = path.basename(file, path.extname(file));
            fileToBaseName[file] = baseName;
        });
        
        // 处理每个文件
        for (const file of imageFiles) {
            const filePath = path.join(sourceDir, file);
            const baseName = path.basename(file, path.extname(file));
            const outputFileName = `${baseName}.png`;
            const outputPath = path.join(outputDir, outputFileName);
            
            console.log(`Processing ${file} to ${outputFileName}...`);
            
            try {
                // 复制文件而不是转换（由于AVIF转换的问题）
                await convertImage(filePath, outputPath);
                
                // 添加到映射表
                fileNameMap[file] = `png/${outputFileName}`;
                fileNameMap[baseName] = `png/${outputFileName}`;
                
                console.log(`Processed ${file} to ${outputFileName}`);
            } catch (error) {
                console.error(`Error processing ${file}:`, error);
            }
        }
        
        console.log('All images processed successfully!');
        
        // 更新JS文件中的路径
        updateJsFile(imageReferences);
        
    } catch (error) {
        console.error('Error processing files:', error);
    }
};

// 更新JS文件中的图片路径
const updateJsFile = (imageReferences) => {
    try {
        console.log(`Updating image paths in ${jsFilePath}...`);
        
        let jsContent = fs.readFileSync(jsFilePath, 'utf8');
        let replacementCount = 0;
        
        // 尝试替换所有占位图片URL为我们的新图片 - 直接映射到特定文件
        const imageMapping = {
            'breakfast1.jpg': 'sanmingzhi.png',
            'breakfast2.jpg': 'yanmaishuiguozhou.png',
            'lunch1.jpg': 'qingjiaoshishu.png',
            'lunch2.jpg': 'sanwenyu.png',
            'dinner1.jpg': 'paigutang.png',
            'dinner2.jpg': 'qingzhengluyu.png',
            'snack1.jpg': 'shuiguoshala.png',
            'snack2.jpg': 'nengliangbang.png',
            'soup1.jpg': 'fanqiedanhua.png',
            'soup2.jpg': 'yumipaigu.png',
            'vegetable1.jpg': 'xilanhua.png',
            'vegetable2.jpg': 'doufu.png'
        };
        
        // 替换所有占位图片
        if (imageReferences.includes('https://img.yzcdn.cn/vant/cat.jpeg')) {
            // 根据图片类别为每个占位符分配特定的图片
            let replacementMap = {};
            let i = 0;
            
            // 对每个图片引用，分配一个图片
            imageReferences.forEach(ref => {
                if (ref === 'https://img.yzcdn.cn/vant/cat.jpeg') {
                    // 获取菜谱项目的类别
                    const lines = jsContent.split('\n');
                    for (let j = 0; j < lines.length; j++) {
                        if (lines[j].includes(ref)) {
                            // 查找周围上下文确定这是哪种类别
                            let categoryLine = '';
                            for (let k = j; k >= Math.max(0, j-10); k--) {
                                if (lines[k].includes('category:')) {
                                    categoryLine = lines[k];
                                    break;
                                }
                            }
                            
                            let replacement = '';
                            if (categoryLine.includes('breakfast')) {
                                replacement = `/images/discovers/png/${categoryLine.includes('1001') ? 'sanmingzhi.png' : 'yanmaishuiguozhou.png'}`;
                            } else if (categoryLine.includes('lunch')) {
                                replacement = `/images/discovers/png/${categoryLine.includes('2001') ? 'qingjiaoshishu.png' : 'sanwenyu.png'}`;
                            } else if (categoryLine.includes('dinner')) {
                                replacement = `/images/discovers/png/${categoryLine.includes('3001') ? 'paigutang.png' : 'qingzhengluyu.png'}`;
                            } else if (categoryLine.includes('snack')) {
                                replacement = `/images/discovers/png/${categoryLine.includes('4001') ? 'shuiguoshala.png' : 'nengliangbang.png'}`;
                            } else if (categoryLine.includes('soup')) {
                                replacement = `/images/discovers/png/${categoryLine.includes('5001') ? 'fanqiedanhua.png' : 'yumipaigu.png'}`;
                            } else if (categoryLine.includes('vegetable')) {
                                replacement = `/images/discovers/png/${categoryLine.includes('6001') ? 'xilanhua.png' : 'doufu.png'}`;
                            } else {
                                // 默认图片
                                const allPngFiles = Object.values(fileNameMap);
                                replacement = `/images/discovers/${allPngFiles[i % allPngFiles.length] || 'png/sanmingzhi.png'}`;
                                i++;
                            }
                            
                            if (replacement) {
                                // 替换当前行的URL
                                const oldLine = lines[j];
                                const newLine = oldLine.replace(`'${ref}'`, `'${replacement}'`).replace(`"${ref}"`, `"${replacement}"`);
                                if (oldLine !== newLine) {
                                    lines[j] = newLine;
                                    replacementCount++;
                                    console.log(`Replaced URL in line ${j+1} with ${replacement}`);
                                }
                            }
                            
                            break;
                        }
                    }
                    
                    jsContent = lines.join('\n');
                }
            });
        }
        
        // 写回文件
        fs.writeFileSync(jsFilePath, jsContent, 'utf8');
        console.log(`Updated ${replacementCount} image references in the JS file.`);
        
    } catch (error) {
        console.error('Error updating JS file:', error);
    }
};

// 辅助函数：转义正则表达式中的特殊字符
function escapeRegExp(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

// 执行转换过程
processFiles(); 